#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <dirent.h>

// 扫描指定目录下的文件
void ScanDirectory(const char *directoryPath) {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(directoryPath);
    if (dir == NULL) {
        perror("Failed to open directory");
        return;
    }

    printf("Files in directory %s:\n", directoryPath);
    while ((entry = readdir(dir))!= NULL) {
        if (entry->d_type == DT_REG) {  // 只打印普通文件
            printf("%s\n", entry->d_name);
        }
    }
    closedir(dir);
}

// 监控指定目录的文件变化
void WatchDirectoryChanges(const char *directoryPath) {
    int inotifyFd;
    int watchDescriptor;
    char buffer[1024];
    struct inotify_event *event;
    ssize_t numRead;

    inotifyFd = inotify_init();
    if (inotifyFd == -1) {
        perror("inotify_init failed");
        return;
    }

    watchDescriptor = inotify_add_watch(inotifyFd, directoryPath, IN_CREATE | IN_MODIFY | IN_DELETE);
    if (watchDescriptor == -1) {
        perror("inotify_add_watch failed");
        close(inotifyFd);
        return;
    }

    printf("Monitoring directory %s for changes...\n", directoryPath);
    while (1) {
        numRead = read(inotifyFd, buffer, sizeof(buffer));
        if (numRead == -1) {
            perror("read failed");
            break;
        }
        event = (struct inotify_event *)buffer;
        while ((char *)event < buffer + numRead) {
            if (event->mask & IN_CREATE) {
                printf("File created: %s\n", event->name);
            } else if (event->mask & IN_MODIFY) {
                printf("File modified: %s\n", event->name);
            } else if (event->mask & IN_DELETE) {
                printf("File deleted: %s\n", event->name);
            }
            event = (struct inotify_event *)((char *)event + sizeof(struct inotify_event) + event->len);
        }
    }

    inotify_rm_watch(inotifyFd, watchDescriptor);
    close(inotifyFd);
}